package com.serivice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mapper.BookMapper;
import com.mapper.CategoryMapper;
import com.serivice.BookService;
import com.vo.R;
import com.vo.po.Book;
import com.vo.po.Category;
import com.vo.req.BookQueryDTO;
import com.vo.req.CategoryDTO;
import com.vo.resp.BookQueryVO;
import com.vo.resp.BookVO;
import com.vo.resp.CategoryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 42
 * @date 2025/6/5
 * @Description
 */
@Service
@RequiredArgsConstructor
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    private final CategoryMapper categoryMapper;

    private final BookMapper bookMapper;

    /**
     * 根据条件分页查询
     * @param queryDTO
     * @return
     */
    @Override
    public R<BookQueryVO> listByCondition(BookQueryDTO queryDTO) {


        Page<Book> page = lambdaQuery().eq(queryDTO.getCategoryId() != null, Book::getCategoryId, queryDTO.getCategoryId())
                .page(new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()));

        List<Book> records = page.getRecords();
        if(CollUtil.isEmpty(records)){
            return R.ok(new BookQueryVO(0L,new ArrayList<>()));
        }

        List<Integer> categoryIds = records.stream().map(Book::getCategoryId).collect(Collectors.toList());

        Map<Integer, Category> categoryMap = categoryMapper.selectBatchIds(categoryIds).stream().collect(Collectors.toMap(Category::getId, Function.identity()));

        //封装参数
        List<BookVO> vo = new ArrayList<>();
        for (Book record : records) {
            BookVO bookVO = BeanUtil.copyProperties(record, BookVO.class);
            bookVO.setCategoryName(categoryMap.get(record.getCategoryId()).getCategoryName());
            vo.add(bookVO);

        }

        BookQueryVO bookQueryVO = new BookQueryVO();
        bookQueryVO.setTotal(page.getTotal());
        bookQueryVO.setData(vo);


        return R.ok(bookQueryVO);
    }

    /**
     * 删除图书
     * @param id
     * @return
     */
    @Override
    public R deleteBook(Integer id) {
        removeById(id);
        return R.ok();
    }

    /**
     * 新增图书
     * @param book
     * @return
     */
    @Override
    public R addBook(Book book) {
        save(book);
        return R.ok();
    }

    /**
     * 修改图书
     * @param book
     * @return
     */
    @Override
    public R updateBook(Book book) {
        updateById(book);
        return R.ok();
    }

    /**
     * 图书分类
     * @return
     */
    @Override
    public R<List<CategoryVO>> getCategoryData() {
        //查询各类别的id和数量
        List<CategoryDTO> dto = bookMapper.getCategoryData();
        if(CollUtil.isEmpty(dto)){
            return R.ok(new ArrayList<>());
        }
        //组装map，key为categoryId,value为categoryName
        Set<Integer> categoryIds = new HashSet<>();
        for (CategoryDTO categoryDTO : dto) {
            categoryIds.add(categoryDTO.getCategoryId());
        }
        Map<Integer, String> categoryMap = categoryMapper.selectBatchIds(categoryIds).stream().collect(Collectors.toMap(Category::getId, Category::getCategoryName));
        //封装数据
        List<CategoryVO> list = new ArrayList<>();
        for (CategoryDTO categoryDTO : dto) {
            CategoryVO categoryVO = new CategoryVO();
            categoryVO.setValue(categoryDTO.getValue());
            categoryVO.setName(categoryMap.get(categoryDTO.getCategoryId()));
            list.add(categoryVO);
        }
        return R.ok(list);
    }

    /**
     * 图书价格统计
     * @return
     */
    @Override
    public R<List<Integer>> getPriceData() {
        List<Map<String, Object>> result = bookMapper.countBooksByPriceRange();
        // 定义标准区间顺序
        List<String> order = Arrays.asList("0-50", "50-100", "100-200", "200-500", "500+");
        // 创建一个默认值为 0 的 map
        Map<String, Integer> resultMap = new HashMap<>();
        for (String range : order) {
            resultMap.put(range, 0);
        }
        // 填充实际数据
        for (Map<String, Object> map : result) {
            String key = (String) map.get("price_range");
            Integer count = ((Number) map.get("count")).intValue();
            if (resultMap.containsKey(key)) {
                resultMap.put(key, count);
            }
        }
        // 按照固定顺序输出 list
        return R.ok(order.stream()
                .map(resultMap::get)
                .collect(Collectors.toList()));
    }

}
